package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TicketMovieShowTime;
import com.ruoyi.system.service.ITicketMovieShowTimeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TicketOrder;
import com.ruoyi.system.service.ITicketOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订票订单信息Controller
 * 
 * @author ruoyi
 * @date 2022-01-10
 */
@Controller
@RequestMapping("/system/ticketorder")
public class TicketOrderController extends BaseController
{
    private String prefix = "system/ticketorder";

    @Autowired
    private ITicketOrderService ticketOrderService;

    @Autowired
    private ITicketMovieShowTimeService ticketMovieShowTimeService;


    @RequiresPermissions("system:ticketorder:view")
    @GetMapping()
    public String ticketorder()
    {
        return prefix + "/ticketorder";
    }

    /**
     * 查询订票订单信息列表
     */
    @RequiresPermissions("system:ticketorder:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TicketOrder ticketOrder)
    {
        startPage();
        List<TicketOrder> list = ticketOrderService.selectTicketOrderList(ticketOrder);
        return getDataTable(list);
    }

    /**
     * 导出订票订单信息列表
     */
    @RequiresPermissions("system:ticketorder:export")
    @Log(title = "订票订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TicketOrder ticketOrder)
    {
        List<TicketOrder> list = ticketOrderService.selectTicketOrderList(ticketOrder);
        ExcelUtil<TicketOrder> util = new ExcelUtil<TicketOrder>(TicketOrder.class);
        return util.exportExcel(list, "订票订单信息数据");
    }

    /**
     * 新增订票订单信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订票订单信息
     */
    @RequiresPermissions("system:ticketorder:add")
    @Log(title = "订票订单信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TicketOrder ticketOrder)
    {
        logger.debug("添加的订单信息="+ticketOrder);
        if(ticketOrder.getTicketCount() < 1)
        {
            ticketOrder.setTicketCount(1);//最少一张票
        }
        ticketOrder.setOrderTime(DateUtils.getNowDate());
        TicketMovieShowTime ticketMovieShowTime =  this.ticketMovieShowTimeService.selectTicketMovieShowTimeById(ticketOrder.getShowTimeId());
        if(null == ticketMovieShowTime)
        {
            return  AjaxResult.error("请求的电影场次不存在！");
        }
        if(ticketMovieShowTime.getLeftCount() < ticketOrder.getTicketCount())
        {
            return  AjaxResult.error("请求的电影场次余票不足！");
        }

        //检查坐次是是否有效
        String message = checkOrderErrorMessage(ticketMovieShowTime, ticketOrder);
        if(StringUtils.isNotEmpty(message))
        {
            return AjaxResult.error(message);
        }

        //修改操作者
        ticketOrder.setOperateId(ShiroUtils.getUserId());
        ticketOrder.setOperateName(ShiroUtils.getLoginName());

        //更新余票
        ticketMovieShowTime.setLeftCount(ticketMovieShowTime.getLeftCount()-ticketOrder.getTicketCount());
        ticketMovieShowTime.setSoldCount(ticketMovieShowTime.getSoldCount()+ticketOrder.getTicketCount());
        this.ticketMovieShowTimeService.updateTicketMovieShowTime(ticketMovieShowTime);

        return toAjax(ticketOrderService.insertTicketOrder(ticketOrder));
    }

    //订单不合法数据错误码
    private String checkOrderErrorMessage(TicketMovieShowTime ticketMovieShowTime, TicketOrder ticketOrder)
    {
//        ticketOrder.getSeatId().split(",");
        List<String> list = StringUtils.str2List(ticketOrder.getSeatId(), ",", true, true);
        //step1：订票数和座位是否匹配
        if(list.size() != ticketOrder.getTicketCount())
        {
            return "订票量与选座个数不符！多个订座号用逗号分隔";
        }
        //step2：是否有重复座位
        List<String> tempList = new ArrayList<String>() ;
        for(String temp : list)
        {
            if(!tempList.contains(temp))
            {
                tempList.add(temp);
            }
        }
        if(tempList.size() != list.size())
        {
            return "选座中包含重复座位！";
        }

        //step3:座位是否已经出售
//        ArrayList<String> seatList =  this.ticketOrderService.selectTicketOrderSeatList(ticketMovieShowTime.getId());
//        for(String temp : seatList)
//        {
//            if(list.contains(temp))
//            {
//                //如果这个座位的订单
//                return "选定的座位["+temp+"]已经出售！请重选座位";
//            }
//        }
        TicketOrder orderCondition = new TicketOrder();
        //查看指定场次的出售座位情况
        orderCondition.setShowTimeId(ticketMovieShowTime.getId());
        List<TicketOrder> orderList = this.ticketOrderService.selectTicketOrderList(orderCondition);
        for(TicketOrder order : orderList)
        {
            List<String> soldSeatList = StringUtils.str2List(order.getSeatId(), ",", true, true);
            //判断soldSeatList 和 list 是否有交集
            for(String tempSeat : soldSeatList)
            {
                if(list.contains(tempSeat))
                {
                    //step4:判断该座的订单 是否本订单，是的话，表示订单修改编辑
                    if(ticketOrder.getId() == order.getId())
                    {
                        continue;
                    }

                    //step5:给出提醒，座位已出售
                    return "选定的座位["+tempSeat+"]已经出售！请重选座位";
                }
            }
        }

        return "";
    }

    /**
     * 修改订票订单信息
     */
    @RequiresPermissions("system:ticketorder:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TicketOrder ticketOrder = ticketOrderService.selectTicketOrderById(id);
        mmap.put("ticketOrder", ticketOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存订票订单信息
     */
    @RequiresPermissions("system:ticketorder:edit")
    @Log(title = "订票订单信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TicketOrder ticketOrder)
    {
        //原来的订票信息
        TicketOrder oldTicketOrder = this.ticketOrderService.selectTicketOrderById(ticketOrder.getId());

        int changeCount = ticketOrder.getTicketCount() - oldTicketOrder.getTicketCount();

        if(ticketOrder.getTicketCount() < 1)
        {
            ticketOrder.setTicketCount(1);//最少一张票
        }
        ticketOrder.setOrderTime(DateUtils.getNowDate());
        TicketMovieShowTime ticketMovieShowTime =  this.ticketMovieShowTimeService.selectTicketMovieShowTimeById(ticketOrder.getShowTimeId());
        if(null == ticketMovieShowTime)
        {
            return  AjaxResult.error("请求的电影场次不存在！");
        }
        if(ticketMovieShowTime.getLeftCount() < changeCount)
        {
            return  AjaxResult.error("请求的电影场次余票不足！");
        }

        //检查坐次是是否有效
        String message = checkOrderErrorMessage(ticketMovieShowTime, ticketOrder);
        if(StringUtils.isNotEmpty(message))
        {
            return AjaxResult.error(message);
        }

        //修改操作者
        ticketOrder.setOperateId(ShiroUtils.getUserId());
        ticketOrder.setOperateName(ShiroUtils.getLoginName());

        //更新余票
        ticketMovieShowTime.setLeftCount(ticketMovieShowTime.getLeftCount()-changeCount);
        ticketMovieShowTime.setSoldCount(ticketMovieShowTime.getSoldCount()+changeCount);
        this.ticketMovieShowTimeService.updateTicketMovieShowTime(ticketMovieShowTime);

        return toAjax(ticketOrderService.updateTicketOrder(ticketOrder));
    }

    /**
     * 删除订票订单信息
     */
    @RequiresPermissions("system:ticketorder:remove")
    @Log(title = "订票订单信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        logger.debug("删除的订单号="+ids+",count="+ids.split(",").length);
        int ticketCount = 0;// ids.split(",").length;
        long id0 = Long.parseLong(ids.split(",")[0]);
        String[] idsarray = ids.split(",");
        for(String idtemp : idsarray)
        {
            if(StringUtils.isNotEmpty(idtemp))
            {
                TicketOrder ticketOrder =  this.ticketOrderService.selectTicketOrderById(Long.parseLong(idtemp));
//                ticketCount += tempOrder.getTicketCount();//累计总票数

                TicketMovieShowTime ticketMovieShowTime =  this.ticketMovieShowTimeService.selectTicketMovieShowTimeById(ticketOrder.getShowTimeId());
                logger.debug("查找到的场次信息="+(ticketMovieShowTime));
                if(null != ticketMovieShowTime)
                {
                   // return  AjaxResult.error("请求的电影场次不存在！");
                    //更新余票
                    ticketMovieShowTime.setLeftCount(ticketMovieShowTime.getLeftCount()+ticketCount);
                    ticketMovieShowTime.setSoldCount(ticketMovieShowTime.getSoldCount()-ticketCount);
                    this.ticketMovieShowTimeService.updateTicketMovieShowTime(ticketMovieShowTime);
                }
            }
        }

        return toAjax(ticketOrderService.deleteTicketOrderByIds(ids));
    }

    /**
     * 查看场次坐席情况
     */
    @GetMapping("/showtimeseat")
    public String showtimeseat()
    {
        return prefix + "/showtimeseat";
    }


    /**
     * 查看坐席情况 id 为电影场次ID
     */
    @PostMapping("/showtimeseatlist/{id}")
    @ResponseBody
    public TableDataInfo showtimeseatlist(@PathVariable("id") Long id)
    {
        TableDataInfo rspData = new TableDataInfo();
        List<SeatNumberModel> userList = new ArrayList<SeatNumberModel>();
        //测试数据

        TicketOrder orderCondition = new TicketOrder();
        //查看指定场次的出售座位情况
        orderCondition.setShowTimeId(id);//ticketMovieShowTime.getId());
        List<TicketOrder> orderList = this.ticketOrderService.selectTicketOrderList(orderCondition);
        //所有售出的座位
        List<String> totalSoldList = new ArrayList<>();
        for(TicketOrder order : orderList)
        {
            List<String> soldSeatList = StringUtils.str2List(order.getSeatId(), ",", true, true);
            totalSoldList.addAll(soldSeatList);
        }
        //电影场次情况
        TicketMovieShowTime ticketMovieShowTime = this.ticketMovieShowTimeService.selectTicketMovieShowTimeById(id);
        int seatCount = ticketMovieShowTime.getTicketCount();

        List<Integer> stateList = new ArrayList<Integer>(10);
        int readCount = 0;
        for(int seatNum = 1; seatNum < seatCount; seatNum ++)
        {
            logger.debug("遍历座位num="+seatNum+",stateList = "+stateList.size()+",readCount="+readCount);
            stateList.add(totalSoldList.contains(seatNum+"") ? 1: 2);

            readCount ++;
            if(readCount == 10)
            {
                //初始化列表
                userList.add(new SeatNumberModel(stateList));
                readCount = 0;
                stateList = new ArrayList<>(10);
            }
        }
        if(readCount != 0)
        {
            userList.add(new SeatNumberModel(stateList));
        }

        int hangCount = seatCount /10;
        int yuCount = seatCount % 10;
        logger.debug("票数="+seatCount+",行数="+hangCount+",列数="+yuCount);

        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (null == pageDomain.getPageNum() || null == pageDomain.getPageSize())
        {
            rspData.setRows(userList);
            rspData.setTotal(userList.size());
            return rspData;
        }

        int totalCount = userList.size();//
        Integer pageNum = (pageDomain.getPageNum() - 1) * totalCount;
        Integer pageSize = pageDomain.getPageNum() * totalCount;
        logger.debug("页面序号pageNum="+pageNum+",页面大小="+pageSize);
        if (pageSize > userList.size())
        {
            pageSize = userList.size();
        }
        rspData.setRows(userList.subList(pageNum, pageSize));
        rspData.setTotal(userList.size());
        return rspData;
    }

    class SeatNumberModel
    {
        //第1列，值为-1表示座位不存在
        private int column1 = 1;
        //第2列，值为-1表示座位不存在
        private int column2 = 2;
        //第3列，值为-1表示座位不存在
        private int column3 = 3;
        //第4列，值为-1表示座位不存在
        private int column4 = 4;
        //第5列，值为-1表示座位不存在
        private int column5 = 5;
        //第6列，值为-1表示座位不存在
        private int column6 = 6;
        //第7列，值为-1表示座位不存在
        private int column7 = 7;
        //第8列，值为-1表示座位不存在
        private int column8 = 8;
        //第9列，值为-1表示座位不存在
        private int column9 = 9;
        //第10列，值为-1表示座位不存在
        private int column10 = 10;

        public SeatNumberModel(List<Integer> stateList) {
            if(stateList.size() < 10) {
                int size = stateList.size();
                for (int index = size; index < 10; index++)
                {
                    stateList.add(-1);
                }
            }
            logger.debug("初始化对象个数=" + stateList.size()+",list="+stateList);
            this.setColumn1(stateList.get(0));
            this.setColumn2(stateList.get(1));
            this.setColumn3(stateList.get(2));
            this.setColumn4(stateList.get(3));
            this.setColumn5(stateList.get(4));
            this.setColumn6(stateList.get(5));
            this.setColumn7(stateList.get(6));
            this.setColumn8(stateList.get(7));
            this.setColumn9(stateList.get(8));
            this.setColumn10(stateList.get(9));
        }

        public int getColumn1() {
            return column1;
        }

        public void setColumn1(int column1) {
            this.column1 = column1;
        }

        public int getColumn2() {
            return column2;
        }

        public void setColumn2(int column2) {
            this.column2 = column2;
        }

        public int getColumn3() {
            return column3;
        }

        public void setColumn3(int column3) {
            this.column3 = column3;
        }

        public int getColumn4() {
            return column4;
        }

        public void setColumn4(int column4) {
            this.column4 = column4;
        }

        public int getColumn5() {
            return column5;
        }

        public void setColumn5(int column5) {
            this.column5 = column5;
        }

        public int getColumn6() {
            return column6;
        }

        public void setColumn6(int column6) {
            this.column6 = column6;
        }

        public int getColumn7() {
            return column7;
        }

        public void setColumn7(int column7) {
            this.column7 = column7;
        }

        public int getColumn8() {
            return column8;
        }

        public void setColumn8(int column8) {
            this.column8 = column8;
        }

        public int getColumn9() {
            return column9;
        }

        public void setColumn9(int column9) {
            this.column9 = column9;
        }

        public int getColumn10() {
            return column10;
        }

        public void setColumn10(int column10) {
            this.column10 = column10;
        }
    }
}
